<template>
	<el-card shadow="hover">
		<el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
			<el-form-item label="优惠券名称" prop="name">
				<el-input v-model="queryParams.name" placeholder="优惠券名称" clearable />
			</el-form-item>
			<el-form-item label="开始时间" prop="start_time">
				<el-date-picker v-model="queryParams.start_time" type="datetime" clearable value-format="X" placeholder="请选择开始时间" />
			</el-form-item>
			<el-form-item label="结束时间" prop="end_time">
				<el-date-picker v-model="queryParams.end_time" type="datetime" clearable value-format="X" placeholder="请选择结束时间" />
			</el-form-item>
			<el-form-item label="类型" prop="way">
				<el-select v-model="queryParams.way">
					<el-option label="全部" value="" />
					<el-option label="全场通用" value="1" />
					<el-option label="指定商品" value="2" />
				</el-select>
			</el-form-item>
			<el-form-item label="优惠券状态" prop="status">
				<el-select v-model="queryParams.status">
					<el-option label="全部" value="" />
					<el-option label="启用" value="1" />
					<el-option label="禁用" value="2" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="onQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="onResetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="top-block mt8 mb8">
			<el-col :span="1.5">
				<el-button @click="onCouponAdd" type="primary" plain icon="el-icon-plus">添加</el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
		</el-row>
		<el-table :data="tableList" v-loading="loading">
			<el-table-column label="ID" align="center" prop="id" />
			<el-table-column label="优惠券名称" align="center" prop="name" />
			<el-table-column label="开始时间" align="center" prop="start_time" :formatter="formatterStartTime" />
			<el-table-column label="结束时间" align="center" prop="end_time" :formatter="formatterEndTime" />
			<el-table-column label="使用方式" align="center" prop="way" :formatter="formatterWay" />
			<el-table-column label="发放方式" align="center" prop="grant_way" :formatter="formatterGrantWay" />
			<el-table-column label="最低消费" align="center" prop="money_full" />
			<el-table-column label="优惠金额" align="center" prop="money" />
			<el-table-column label="用户可领取数" align="center" prop="receive_rule" />
			<el-table-column label="优惠券数量" align="center" prop="num" />
			<el-table-column label="剩余库存" align="center" prop="num_stock" />
			<!-- <el-table-column label="说明" align="center" prop="illustrate">
				<template #default="scope">
					<el-tooltip v-if="scope.row.illustrate" effect="light" :content="scope.row.illustrate" placement="top">
						<el-button>查看</el-button>
					</el-tooltip>
					<span v-else>----</span>
				</template>
			</el-table-column> -->
			<el-table-column label="状态" align="center" prop="status">
				<template #default="scope">
					<el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="onChangeStatus(scope.row)" />
				</template>
			</el-table-column>
			<el-table-column label="排序" align="center" prop="sort" />
			<el-table-column label="创建时间" align="center" prop="create_time" :formatter="formatterCreateTime" />
			<el-table-column label="操作" align="center" fixed="right">
				<template #default="{ row }">
					<el-button @click="onCouponView(row)" type="text">查看</el-button>
					<el-button @click="onCouponEdit(row)" type="text">修改</el-button>
					<el-button @click="onCouponStock(row)" type="text">修改库存</el-button>
					<el-button v-if="row.grant_way === 2" @click="onCouponManualProvisioning(row)" type="text">后台发放</el-button>
					<el-button v-if="row.grant_way === 2" @click="onBatchImport(row)" type="text">批量导入发放人员</el-button>
					<el-button v-if="row.grant_way === 2" @click="onViewIssueRecords(row)" type="text">查看发放记录</el-button>
					<el-button @click="onViewGetRecords(row)" type="text">查看领取记录</el-button>
					<el-button @click="onClearCouponHistory(row)" type="text">清空领取记录</el-button>
					<el-button @click="onViewUsageHistory(row)" type="text">查看使用记录</el-button>
					<el-button @click="onCouponDelete(row)" type="text" style="color: #f56c6c">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination-component
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>

		<coupon-add-dialog ref="couponAddRef" />
		<coupon-edit-dialog ref="couponEditRef" />
		<coupon-view-dialog ref="couponViewRef" />
		<coupon-stock-edit-dialog ref="couponStockEditRef" />
		<coupon-manual-provisioning-dialog ref="couponManualProvisioningDialogRef" />
		<view-usage-history-dialog ref="viewUsageHistoryDialogRef" />
		<view-issue-records-dialog ref="viewIssueRecordsDialogRef" />
		<view-get-records-dialog ref="viewGetRecordsDialogRef" />
		<batch-impor-dialog ref="batchImporDialogRef" />
	</el-card>
</template>

<script lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { couponApi } from '/@/api/admin';
import { timeDictionary, endTimePlus } from '/@/utils/dictionaryTranslation';
import couponAddDialog from './dialog/couponAddDialog.vue';
import couponEditDialog from './dialog/couponEditDialog.vue';
import couponViewDialog from './dialog/couponViewDialog.vue';
import couponStockEditDialog from './dialog/couponStockEditDialog.vue';
import couponManualProvisioningDialog from './dialog/couponManualProvisioningDialog.vue';
import viewUsageHistoryDialog from './dialog/viewUsageHistoryDialog.vue';
import viewIssueRecordsDialog from './dialog/viewIssueRecordsDialog.vue';
import viewGetRecordsDialog from './dialog/viewGetRecordsDialog.vue';
import batchImporDialog from './dialog/batchImporDialog.vue';

export default {
	name: 'goodCoupon',
	components: {
		couponAddDialog,
		couponEditDialog,
		couponViewDialog,
		couponStockEditDialog,
		couponManualProvisioningDialog,
		viewUsageHistoryDialog,
		viewIssueRecordsDialog,
		batchImporDialog,
		viewGetRecordsDialog,
	},
	setup() {
		const CouponApi = couponApi();

		const queryFormRef = ref(null);
		const couponAddRef = ref(null);
		const couponViewRef = ref(null);
		const couponEditRef = ref(null);
		const couponStockEditRef = ref(null);
		const couponManualProvisioningDialogRef = ref(null);
		const viewUsageHistoryDialogRef = ref();
		const viewIssueRecordsDialogRef = ref();
		const viewGetRecordsDialogRef = ref();
		const batchImporDialogRef = ref();

		const loadingExportRef = ref(null);
		const state = reactive({
			single: true, // 非单个禁用
			multiple: true, // 非多个禁用
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				name: '',
				type: '', // 类型 1：满减券 2：折扣券
				way: '', // 1-全场通用，2-指定商品
				goods_id: '',
				status: '', // 1：启用 0：禁用
				start_time: '',
				end_time: '',
			},
			supplierIdOptions: [] as any,
			isJicaiOptions: [
				{
					label: '全部',
					value: 0,
				},
				{
					label: '普通商品',
					value: 1,
				},
				{
					label: '采集商品',
					value: 2,
				},
			],
			showSearch: true,
			tableList: [],
			loading: false,
			total: 0,
			wayOptions: [
				{
					value: '1',
					label: '全场通用',
				},
				{
					value: '2',
					label: '指定商品',
				},
			],
		});

		onMounted(() => {
			getList();
		});

		/********** 点击事件(on开头) **********/
		// 搜索
		const onQuery = () => {
			state.queryParams.pageNum = 1;
			getList();
		};
		// 重置
		const onResetQuery = () => {
			(queryFormRef.value as any)?.resetFields();
			onQuery();
		};
		// 批量导入优惠券
		const onBatchImport = (row: any) => {
			(batchImporDialogRef.value as any)?.openDialog({ row }, () => getList());
		};
		// 添加优惠券
		const onCouponAdd = () => {
			(couponAddRef.value as any)?.openDialog({}, () => getList());
		};
		// 修改优惠券
		const onCouponEdit = (row: any) => {
			(couponEditRef.value as any)?.openDialog({ row }, () => getList());
		};
		// 手动优惠券
		const onCouponManualProvisioning = (row: any) => {
			(couponManualProvisioningDialogRef.value as any)?.openDialog({ row }, () => getList());
		};
		// 查看优惠券
		const onCouponView = (row: any) => {
			(couponViewRef.value as any)?.openDialog({ row });
		};
		// 修改优惠券库存
		const onCouponStock = (row: any) => {
			(couponStockEditRef.value as any)?.openDialog({ row }, () => getList());
		};
		// 清空优惠券
		const onClearCouponHistory = (row: any) => {
			ElMessageBox.prompt('您确定要清除此条优惠券领取记录吗?', '确认消息', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				inputPlaceholder: '请输入操作密码',
			}).then(({ value }) => {
				_couponEmpty({ coupon_id: row.id, password: value });
			});
		};
		// 查看使用记录
		const onViewUsageHistory = (row: any) => {
			viewUsageHistoryDialogRef.value.openDialog({ row });
		};
		// 查看发放记录
		const onViewIssueRecords = (row: any) => {
			viewIssueRecordsDialogRef.value.openDialog({ row });
		};
		// 查看领取记录
		const onViewGetRecords = (row: any) => {
			viewGetRecordsDialogRef.value.openDialog({ row });
		};
		// 删除优惠券
		const onCouponDelete = (row: any) => {
			ElMessageBox.prompt('您确定要删除此条优惠券?', '确认消息', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				inputPlaceholder: '请输入操作密码',
			}).then(({ value }) => {
				_couponDelete({ coupon_id: row.id, password: value });
			});
		};
		// 启用、禁用
		const onChangeStatus = (row: any) => {
			ElMessageBox.prompt(`是否确认${Number(row.status) ? '启用' : '禁用'}优惠券编号为${row.id}的数据项？`, '提示', {
				type: 'warning',
				inputPlaceholder: '请输入操作密码',
			})
				.then(({ value }) => {
					CouponApi.couponGoods({ coupon_id: row.id }).then((res: any) => {
						CouponApi.couponEdit({
							...row,
							coupon_id: row.id,
							goods_id: res.data.list.map((item: any) => item.id),
							time: [row.start_time, row.end_time],
							status: row.status,
							password: value,
						})
							.then(() => {
								ElMessage.success(`${Number(row.status) ? '启用' : '禁用'}成功`);
							})
							.catch(() => {
								row.status = row.status ? 0 : 1;
							});
					});
				})
				.catch(() => {
					row.status = row.status ? 0 : 1;
				});
		};

		/********** 方法事件 **********/
		const getList = () => {
			state.loading = true;
			_couponList({
				...state.queryParams,
				end_time: endTimePlus(state.queryParams.start_time, state.queryParams.end_time),
			});
		};
		// 使用方式字典
		const formatterWay = (row: any) => {
			return row.way === 1 ? '全场通用' : '指定商品';
		};
		// 发放方式字典
		const formatterGrantWay = (row: any) => {
			return row.grant_way === 1 ? '自己领取' : '后台发放';
		};
		// 开始时间
		const formatterStartTime = (row: any) => {
			return timeDictionary(row.start_time);
		};
		// 结束时间
		const formatterEndTime = (row: any) => {
			return timeDictionary(row.end_time);
		};
		// 创建时间
		const formatterCreateTime = (row: any) => {
			return timeDictionary(row.create_time);
		};

		/********** 网络事件 **********/
		// 优惠券列表
		const _couponList = (_data: object) => {
			CouponApi.couponList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 删除优惠券
		const _couponDelete = (params: any) => {
			CouponApi.couponDelete(params)
				.then(() => {
					ElMessage.success('操作成功');
					getList();
				})
				.catch(() => {});
		};
		// 清空优惠券领取记录
		const _couponEmpty = (params: any) => {
			CouponApi.couponEmpty(params).then(() => {
				ElMessage.success('操作成功');
			});
		};
		return {
			queryFormRef,
			couponAddRef,
			couponEditRef,
			couponViewRef,
			loadingExportRef,
			couponStockEditRef,
			couponManualProvisioningDialogRef,
			viewUsageHistoryDialogRef,
			viewIssueRecordsDialogRef,
			viewGetRecordsDialogRef,
			batchImporDialogRef,
			timeDictionary,
			onQuery,
			onResetQuery,
			onCouponAdd,
			onChangeStatus,
			onCouponEdit,
			onCouponManualProvisioning,
			onCouponStock,
			onCouponView,
			onCouponDelete,
			onClearCouponHistory,
			onViewUsageHistory,
			onViewIssueRecords,
			onViewGetRecords,
			onBatchImport,
			getList,
			formatterWay,
			formatterStartTime,
			formatterEndTime,
			formatterCreateTime,
			formatterGrantWay,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped></style>
